package com.jcsz.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.jcsz.common.exception.NoStockException;
import com.jcsz.common.to.mq.OrderTo;
import com.jcsz.common.to.mq.StockDetailTo;
import com.jcsz.common.to.mq.StockLockedTo;
import com.jcsz.common.utils.R;
import com.jcsz.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.jcsz.gulimall.ware.entity.WareOrderTaskEntity;
import com.jcsz.gulimall.ware.feign.OrderFeignService;
import com.jcsz.gulimall.ware.feign.SkuInfoService;
import com.jcsz.gulimall.ware.service.WareOrderTaskDetailService;
import com.jcsz.gulimall.ware.service.WareOrderTaskService;
import com.jcsz.gulimall.ware.vo.OrderVo;
import com.jcsz.gulimall.ware.vo.SkuHasStockVo;
import com.jcsz.gulimall.ware.vo.WareSkuLockVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcsz.common.utils.PageUtils;
import com.jcsz.common.utils.Query;

import com.jcsz.gulimall.ware.dao.WareSkuDao;
import com.jcsz.gulimall.ware.entity.WareSkuEntity;
import com.jcsz.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
@Slf4j
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageBycondition(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params), queryWrapper

        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        WareSkuEntity wareSkuEntity = wareSkuDao.selectOne(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (wareSkuEntity == null) {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setWareId(wareId);
            skuEntity.setStock(skuNum);
            try {
                R result = skuInfoService.info(skuId);
                Map<String, Object> map = (Map<String, Object>) result.get("skuInfo");
                if (result.getCode() == 200) {
                    skuEntity.setSkuName((String) map.get("skuName"));

                }
            } catch (Exception exception) {

            }
            this.save(skuEntity);
        } else {
            wareSkuDao.updateStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStocks(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(item -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long stock = wareSkuDao.getStockBySpuId(item);
            skuHasStockVo.setSkuId(item);
            skuHasStockVo.setHasStock(stock == null ? false : stock > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    @Transactional
    public Boolean orderLockStock(WareSkuLockVo wareSkuLockVo) {
        /**
         * 库存锁定前保存工单
         **/
        WareOrderTaskEntity wareOrderTask = new WareOrderTaskEntity();
        wareOrderTask.setOrderSn(wareSkuLockVo.getOrderSn());
        wareOrderTaskService.save(wareOrderTask);

        List<SkuWareHasStock> collect = wareSkuLockVo.getLocks().stream().map((item) -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            stock.setSkuId(item.getSkuId());
            stock.setNum(item.getCount());
            List<Long> wareIds = baseMapper.listWareIdHasSkuStock(item.getSkuId());
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());
        for (SkuWareHasStock stock : collect) {
            boolean skuStocked = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if (StringUtils.isEmpty(wareIds)) {
                //没有任何仓库有这个商品的库存
                throw new NoStockException(skuId);
            }
            //1、如果每一个商品都锁定成功,将当前商品锁定了几件的工作单记录发给MQ
            //2、锁定失败。前面保存的工作单信息都回滚了。发送出去的消息，即使要解锁库存，由于在数据库查不到指定的id，所有就不用解锁
            for (Long id : wareIds) {
                Long result = baseMapper.lockSkuStock(skuId, id, stock.getNum());
                if (result == 1) {
                    skuStocked = true;
                    //库存锁定成功,发送消息
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null, stock.getSkuId(), "", stock.getNum(), wareOrderTask.getId(), id, 1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    //TODO 告诉MQ库存锁定成功
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(wareOrderTask.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    stockLockedTo.setDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);
                    break;
                } else {
                    //当前仓库锁失败，重试下一个仓库
                }
            }
            if (!skuStocked) {
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

    public void unLockStock(StockLockedTo stockLockedTo) {
        Long taskId = stockLockedTo.getId();
        StockDetailTo detailTo = stockLockedTo.getDetailTo();
        WareOrderTaskDetailEntity newDetailTo = wareOrderTaskDetailService.getById(detailTo.getId());
        //间隔时间到了,收到消息,工单详情不为空
        //需要解锁的条件   1.查看订单状态,
        if (newDetailTo != null) {
            WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getById(taskId);
            R info = orderFeignService.info(orderTaskEntity.getOrderSn());
            if (info.getCode() == 200) {
                OrderVo data = info.getData(new TypeReference<OrderVo>() {
                });
                //订单不存在,或者订单已关闭,解锁库存
                if (data == null || data.getStatus() == 4) {
                    //反向补偿
                    if (newDetailTo.getLockStatus() == 1) {
                        unLockStock(newDetailTo.getSkuId(), newDetailTo.getSkuNum(), newDetailTo.getWareId(), newDetailTo.getId());
                    }
                }
            } else {
                //消息拒绝以后重新放在队列里面，让别人继续消费解锁
                //远程调用服务失败
                throw new RuntimeException("远程服务调用异常......");
            }
        } else {
            //无需解锁
        }
    }

    public void unLockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOne(new QueryWrapper<WareOrderTaskEntity>().eq("order_sn", orderSn));
        //按照工作单的id找到所有 没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> wareOrderTaskDetailEntities = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", wareOrderTaskEntity.getId()).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity detailTo : wareOrderTaskDetailEntities) {
            unLockStock(detailTo.getSkuId(), detailTo.getSkuNum(), detailTo.getWareId(), detailTo.getId());
        }
    }

    private void unLockStock(Long skuId, Integer skuNum, Long wareId, Long deatilId) {
        //库存解锁
        baseMapper.unLockStock(skuId, skuNum, wareId);
        //更新库存工单状态信息
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(deatilId);
        wareOrderTaskDetailEntity.setLockStatus(2);//变为已解锁
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }


}